package com.atguigu.jxc.service.impl;

import com.atguigu.jxc.dao.CustomerDao;
import com.atguigu.jxc.entity.Customer;
import com.atguigu.jxc.entity.Log;
import com.atguigu.jxc.entity.Supplier;
import com.atguigu.jxc.service.CustomerService;
import com.atguigu.jxc.service.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wswdkl
 * @version 1.0
 * @date 2022/2/11 14:46
 */
@Service
public class CustomerServiceImpl implements CustomerService {

    @Autowired
    private CustomerDao customerDao;
    @Autowired
    private LogService logService;

    /**
     * 分页查询客户信息
     * @param page
     * @param rows
     * @param customerName
     * @return
     */
    @Override
    public Map<String, Object> queryCustomerPage(Integer page, Integer rows, String customerName) {
        Map<String, Object> map = new HashMap<>();

        int total = customerDao.getCustomerCount(customerName);
        page = (page == 0 ? 1 : page);
        int offSet = (page - 1) * rows;
        List<Customer> customers = customerDao.queryCustomerPage(offSet, rows, customerName);

        logService.save(new Log(Log.SELECT_ACTION, "分页查询客户信息"));

        map.put("total", total);
        map.put("rows", customers);

        return map;
    }

    /**
     * 添加或者修改客户信息
     * @param customer
     * @return
     */
    @Override
    public boolean saveCustomer(Customer customer) {
        //根据supplier是否有supplierId，可以判断是添加还是修改
        if(customer.getCustomerId() == null) {
            //a.代表是添加
            int insert = customerDao.insertCustomer(customer);
            if(insert >= 1) {
                logService.save(new Log(Log.INSERT_ACTION, "添加用户信息"));
                return true;
            }
        } else {
            //b.代表为修改
            int update = customerDao.updateCustomer(customer);
            if(update >= 1) {
                logService.save(new Log(Log.UPDATE_ACTION,"修改用户信息"));
                return true;
            }
        }
        return false;
    }

    /**
     * 删除客户信息
     * @param ids
     * @return
     */
    @Override
    public boolean deleteCustomer(String ids) {
        String[] idList = ids.split(",");
        int delete = customerDao.deleteCustomer(idList);
        if(delete >= 1) {
            logService.save(new Log(Log.DELETE_ACTION,"删除客户信息"));
            return true;
        }
        return false;
    }
}
